package me.lensfrex.trailblazer.api.v1.config;

import me.lensfrex.trailblazer.api.v1.exceptions.ConfigureFileInvalidException;
import me.lensfrex.trailblazer.api.v1.utils.IOUtil;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class ConfigLoader {



    private final String globalConfigFilePath;

    public ConfigLoader(String globalConfigFilePath) {
        this.globalConfigFilePath = globalConfigFilePath;
    }

    public static String toSpecificPathForm(String uniformFilepath) {
        return uniformFilepath.replace("/", File.separator);
    }

    // todo: 脑子有点乱了，等以后再去重写一遍吧
    public void load() throws ConfigureFileInvalidException {
        try {
            File globalConfigFile = new File(globalConfigFilePath);
            if (!globalConfigFile.exists()) {
                globalConfigFile.getParentFile().mkdirs();
                globalConfigFile.createNewFile();

                InputStream defaultConfigInoutStream = getClass().getResourceAsStream("me/lensfrex/trailblazer/DefaultConfig.conf");
                if (defaultConfigInoutStream == null) {
                    throw new NullPointerException("Can't find the default config file in program.");
                }

                GlobalConfig.configProperties.load(defaultConfigInoutStream);

                String defaultConfig = IOUtil.inputStreamToString(defaultConfigInoutStream, StandardCharsets.UTF_8);
                IOUtil.writeFile(defaultConfig.getBytes(StandardCharsets.UTF_8), globalConfigFile);

                return;
            }
            FileInputStream configFileInputStream = new FileInputStream(globalConfigFile);
            GlobalConfig.configProperties.load(configFileInputStream);

        } catch (FileNotFoundException e) {
            // todo: 这里应该换成使用日志输出
            System.err.printf("Error: Config file: %s doesn't exists.%n", globalConfigFilePath);
            e.printStackTrace();
        } catch (Exception e) {
            // todo: 这里应该换成使用日志输出
            System.err.printf("Error: Some errors happened while reading config file: %s %n", globalConfigFilePath);
            System.err.printf("Error: %s%n", e.getMessage());
            e.printStackTrace();
        }
    }
}
